﻿/**
 * Created with JetBrains PhpStorm.
 * User: Evan Hou
 * Date: 12-8-12
 * Time: 上午12:39
 * To change this template use File | Settings | File Templates.
 */

var dy = {
    'base_url':'http://i.dy1010.com/',
    'img_url':'http://i.dy1010.com/',
    'static_url':'http://i.dy1010.com/',
    'cookie_prefix':'dy_',
    'cookie_domain':'dy1010.com',
    'cookie_path':'/'
};


// 获取Cookie
dy.getCookie = function (name)
{
    name = dy.cookie_prefix+name;

    var arrStr = document.cookie.split("; ");

    for (var i = 0; i < arrStr.length; i++) {
        var temp = arrStr[i].split("=");
        if (temp[0] == name) return unescape(temp[1]);
    }

    return null;
}


// 设置Cookie
dy.setCookie = function (name, value, expires)
{
    var secure;
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));
	document.cookie = dy.cookie_prefix+name+'='+escape(value) +
	( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
	( ( dy.cookie_path ) ? ';path=' + dy.cookie_path : '' ) +
	( ( dy.cookie_domain ) ? ';domain=' + dy.cookie_domain : '' ) +
	( ( secure ) ? ';secure' : '' );
}

// 删除Cookie
dy.deleteCookie = function (name, path, domain)
{
	if (getCookie(name)) document.cookie = dy.cookie_prefix+name + '=' +
	( ( path ) ? ';path=' + path : '') +
	( ( domain ) ? ';domain=' + domain : '' ) +
	';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

// 删除数组包含某元素，并重新构建索引
dy.arr_del = function (arr, d)
{
	return arr.slice(0,d-1).concat(arr.slice(d));
}

// 数组查找返回索引
dy.arr_find = function (arr, d)
{
	var length = arr.length;
	for (var i = 0; i < length; i++) {
		if (arr[i] == d) {
			return i;
		}
	}
	return -1;
}

/* 是否存在于数组 */
dy.inArray = function (value, array)
{
  for (var i=0; i < array.length; i++) {
      if (array[i] == value) return true;
  }
  return false;
}

//AJAX请求
dy.ajax = function (url, parameter)
{
    var msg;
	$.ajax({
	   type : "POST",
	   url  : dy.base_url+url,
	   async: false,
	   data : parameter,
       dataType:'json',
	   success: function(msgs){
			//eval('('+msgs+')');
           msg = msgs;
	   }
	});
	return msg;
}

dy.jsonp = function(url, param, func, _async)
{
    if((typeof _async) == 'undefined')
    {
        _async = true;
    }

    //var result = {};
    //$.getJSON(url + "?"+ $.param(param)+"&callback=?", func); return;

    //var msg;
	$.ajax({
	   type : "GET",
	   url  : dy.base_url+url+"?callback=?",
	   async: _async,
	   data : (param),
       dataType:'json',
	   success: func
	});

	//return msg;
}

//获取单选框的值
dy.getRadioCheckBoxValue = function (RadioName)
{
	var obj;
	obj=document.getElementsByName(RadioName);
	if(obj!=null){
	    var i;
	    for(i=0;i<obj.length;i++){
	        if(obj[i].checked){
	            //return true;
                return obj[i].value;
	        }
	    }
	}
	return false;
}

//获取当前URL的某个参数值
dy.request = function (paras){
	var url = location.href;
	var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
	var paraObj = {}
	for (i=0; j=paraString[i]; i++)
	{
		paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
	}
	var returnValue = paraObj[paras.toLowerCase()];
	if(typeof(returnValue)=="undefined")
	{
		return "";
	}else{
		return returnValue;
	}
}

//是否为邮件地址
dy.isEmail = function ( str ){
    var myReg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;

    return myReg.test(str) ? true : false;
}

//判断是否为空
dy.isEmpty = function(content)
{
    return (content == '' || content == undefined) ? false : true;
}

//判断长度
dy.limit_length = function (str, minLength, maxLength)
{
    if (!dy.isEmpty (str)) {
        return false;
    }

    if (!dy.isEmpty (minLength)) {
        minLength = 6;
    }

    if (!dy.isEmpty (maxLength)) {
        maxLength = 32;
    }

    if (str.length < minLength || str.length > maxLength) {
        return false;
    }

    return true;
}


//获取来源(referer)地址
dy.getReferer = function ()
{
    var referer = document.referrer;

    return dy.isEmpty(referer) ? referer : dy.base_url;
}

//跳转到上一个页面
dy.goToBack = function ()
{
    var url = dy.getReferer();

    if (dy.isEmpty(url) && dy.isUrl(url)) {
        window.location.href = url;
    }

    return false;
}

//收藏
dy.addFavorite = function (title, url)
{
    title = dy.isEmpty(title) ? title : "电影壹零壹零, www.dy1010.com";
    url = dy.isEmpty(url) ? url : dy.base_url+"?fav";

	if(window.sidebar) {
		window.sidebar.addPanel(title,url,'');
	} else {
		try{
			window.external.AddFavorite(url,title);
		} catch(e) {
			alert("您的浏览器不支持该功能,请使用Ctrl+D收藏本页");
		}
	}
}

//设为首页
dy.setHomepage = function () {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage('http://www.dy1010.com');
        alert('设置成功！')
    } else if (window.sidebar) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', 'http://www.dy1010.com');
        alert('设置成功！')
    } else {
        alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
    }
}

//跳转到某个地址
dy.goToUrl = function (url)
{
    //url = dy.base_url+url;

    url = url.split('#');
    url = url[0];
    /*
    if (dy.isUrl(url) ) {
        alert ('不是一个正确的URL地址!');
        return false;
    }
    //*/

    window.location.href = url;
}

//让页面重新加载
dy.pageReload = function (time)
{
    if (time) {
        time = time * 1000;
        setTimeout('window.location.reload()', time);
    } else {
        window.location.reload();
    }
}

//验证手机号码
dy.isMobile = function (value) {
    if (/^13\d{9}$/g.test(value) || (/^15[0-35-9]\d{8}$/g.test(value)) || (/^18[05-9]\d{8}$/g.test(value))) {
        return true;
    } else {
        return false;
    }
}

//判断输入是否为中文
dy.isChinese = function(s) {
    var ret = true;
    for (var i = 0; i < s.length; i++)
        ret = ret && (s.charCodeAt(i) >= 10000);
    return ret;
}

dy.selectRecommend = function (t, id)
{
    $('.r1_right_nav a').attr('id', '');
    $('.r1_right_c').css('display', 'none');

    $('#recommend_list'+id).css('display', 'block');
    $(t).attr('id', 'r1_r_nav_cur');//   r1_r_nav_s
}

//用户是否登陆
dy.isLogin = function ()
{
    var auth = dy.getCookie('auth');

    if (!dy.isEmpty(auth)) {
        return false;
    }

    var url = 'login/getUserInfo';
    var data = dy.ajax(url, '');

    if (data.error == '1009') {
        return false;
    }

    if (data.error == '0') {
        return data.user_info;
    }

    return false;
}

//检查登陆状态
dy.checkLoginStatus = function ()
{
    var auth = dy.getCookie('auth');

    if (!dy.isEmpty(auth)) {
        //dy.loginLayer();
        dy.goToUrl(dy.base_url+'login/index')
        return false;
    }

    var url = 'user/login/getUserInfo';
    var data = dy.ajax(url, '');

    if (data.error == '1009') {
        //dy.loginLayer();
        dy.goToUrl(dy.base_url+'login/index')
        return false;
    }

    if (data.error == '0') {
        return data.user_info;
    }

    //dy.loginLayer();
    dy.goToUrl(dy.base_url+'login/index')
    return false;
}

dy.nopic = function (o)
{
    o.src=dy.base_url+"images/no_pic.jpg";
    o.onerror=null; //防止一直跳动
}



var user = {};

//用户JS库初始化
user.init = function ()
{
    var userName = dy.getCookie('username');

    userName = ( userName == null ) ? '' : userName;
    //console.log(document.getElementById('username_id'));
    if (document.getElementById('username_id')) {
        document.getElementById('username_id').value = userName;
    }

    var uInfo = dy.isLogin();
    if (uInfo) {
        var html = '欢迎您！'+uInfo['username']+'&nbsp;&nbsp;'+'<a href="'+dy.base_url+'login/out">[退出]</a>  |';
        $('#login_status').html(html);
    }
}

//检测用户名
user.checkUserName = function ()
{
    var userName = document.getElementById('username_id').value;

    $('#username_notice_id').html('');
    $("#username_notice_id").removeClass("mistake");
    $("#username_notice_id").removeClass("txi");

    if (!dy.isEmpty (userName)) {
        $("#username_notice_id").removeClass("txi").addClass("mistake");
        $('#username_notice_id').html('用户名为空！');
        return false;
    }

    if (!dy.limit_length(userName, 6, 32)) {
        $("#username_notice_id").removeClass("txi").addClass("mistake");
        $('#username_notice_id').html('用户名小于6位或大于32位！');
        return false;
    }

    /*
    if (!dy.isEmail(userName)) {
        $("#username_notice_id").removeClass("txi").addClass("mistake");
        $('#username_notice_id').html('输入的用户名不为邮件地址！');
        return false;
    }
    //*/

    //将用户名设置成cookie,以便于刷新页面后不需要重新输入
    dy.setCookie('username', userName, 10000000);

    return userName;
}

//检测密码
user.checkPassWord = function ()
{
    var passWord = document.getElementById('password_id').value;

    $('#password_notice_id').html('');
    $("#password_notice_id").removeClass("mistake");
    $("#password_notice_id").removeClass("txi");

    if (!dy.isEmpty (passWord)) {
        $("#password_notice_id").removeClass("txi").addClass("mistake");
        $('#password_notice_id').html('密码为空！');
        return false;
    }

    if (!dy.limit_length(passWord, 6, 32)) {
        $("#password_notice_id").removeClass("txi").addClass("mistake");
        $('#password_notice_id').html('密码小于6位或大于32位！');
        return false;
    }

    return passWord;
}

user.checkLoginIsSubmit = function (e)
{
    if (e.keyCode == 13) {
        user.submitLoginForm();
    }
}

//提交登陆表单
user.submitLoginForm = function ()
{
    $('.tips_box').fadeOut("fast");

    var source = document.getElementById('source_id').value;
    var redirectUrl = document.getElementById('redirect_url_id').value;
    //var remember = dy.getRadioCheckBoxValue('remember') ? 1 : 0;

    var userName = '';
    var passWord = '';

    //console.log(remember);return ;

    if ( !(userName = user.checkUserName()) ) return false;
    if ( !(passWord = user.checkPassWord()) ) return false;

    var url = 'login/submit';
    var param = 'username='+userName+'&password='+passWord+'&source='+source+'&redirect_url='+redirectUrl;
    var data = dy.ajax(url, param);

    if (data.error == '0') {
        dy.goToUrl(data.redirect_url);
        //window.location.href = data.redirect_url;
    }

    $('#message_id').html(data.msg);
    $('.tips_box').fadeIn("slow");
}


//检测重复密码
user.checkRePassWord = function ()
{
    var passWord = user.checkPassWord();
    var rePassWord = document.getElementById('repassword_id').value;

    $('#repassword_notice_id').html('');
    $("#repassword_notice_id").removeClass("mistake");
    $("#repassword_notice_id").removeClass("txi");

    if ( ! passWord ) return false;

    if (!dy.isEmpty (rePassWord)) {
        $("#repassword_notice_id").removeClass("txi").addClass("mistake");
        $('#repassword_notice_id').html('确认密码为空！');
        return false;
    }

    if (!dy.limit_length(rePassWord, 6, 32)) {
        $("#repassword_notice_id").removeClass("txi").addClass("mistake");
        $('#repassword_notice_id').html('确认密码小于6位或大于32位！');
        return false;
    }

    if (passWord != rePassWord) {
        $("#repassword_notice_id").removeClass("txi").addClass("mistake");
        $('#repassword_notice_id').html('两个输入密码不一致！');
        return false;
    }

    return rePassWord;
}

//检查验证码
user.checkVerifyCode = function ()
{
    var verifyCodeCookie = dy.getCookie('verify_code');

    var verifyCodePage = document.getElementById('verify_code_id').value;

    $('#verify_code_notice_id').html('');
    $("#verify_code_notice_id").removeClass("mistake");
    $("#verify_code_notice_id").removeClass("txi");

    if (!dy.isEmpty (verifyCodePage)) {
        $("#verify_code_notice_id").removeClass("txi").addClass("mistake");
        $('#verify_code_notice_id').html('验证码为空！');
        return false;
    }

    var status = '';
    var url = 'register/checkVerifyCode';
    var param = {"verify_code":verifyCodePage};
    var data = dy.ajax(url, param);

    if (data.error == '0') {
        $("#verify_code_notice_id").removeClass("mistake").addClass("txi");
        $('#verify_code_notice_id').html('输入正确！');
        return verifyCodePage;
    } else {
        $("#verify_code_notice_id").removeClass("txi").addClass("mistake");
        $('#verify_code_notice_id').html('验证码错误！');
        return false;
    }
}

//刷新验证码
user.refreshVerifyCode = function ()
{
    var refresh = document.getElementById("verify_code");
    refresh.src = dy.base_url+"register/verifyCode?tempstr=" + Math.random();
}

//检测用户是否存在
user.checkUserExist = function ()
{
    var userName = user.checkUserName();

    if ( ! userName ) return false;

    var url = 'register/checkUserName';
    var param = 'username='+userName;
    var data = dy.ajax(url, param);

    var status;
    switch (data.error) {
        case '10001': status = false; break
        case '10002': status = false; break
        case '10035': status = userName; break
    }

    status ? $("#username_notice_id").removeClass("mistake").addClass("txi") : $("#username_notice_id").removeClass("txi").addClass("mistake");

    $('#username_notice_id').html(data.msg);
    return status;

}

//检测注册是否提交
user.checkRegisterIsSubmit = function (e)
{
    if (e.keyCode == 13) {
        user.submitRegisterForm();
    }
}

//注册表单提交
user.submitRegisterForm = function ()
{
    var source = document.getElementById('source_id').value;
    var redirectUrl = document.getElementById('redirect_url_id').value;
    var agree = dy.getRadioCheckBoxValue('agree') ? 1 : 0;

    var userName = user.checkUserName();
    var passWord = user.checkPassWord();
    var rePassWord = user.checkRePassWord();
    var verifyCode = user.checkVerifyCode();
//console.log(verifyCode);
    if (!agree) {
        alert('请同意万象网服务条款');
    }

    if ( ! userName ) return false;
    if ( ! passWord ) return false;
    if ( ! rePassWord ) return false;
    if ( ! verifyCode ) return false;

    var url = 'register/submit';
    var param = 'username='+userName+'&password='+passWord+'&repassword='+rePassWord+'&source='+source+'&redirect_url='+redirectUrl+'&verify_code='+verifyCode;
    var data = dy.ajax(url, param);

    $('#message_id').html(data.msg);
    $('.tips_box').fadeIn("slow");

    if (data.error == '0') {
        dy.goToUrl(data.redirect_url);
        //window.location.href = data.redirect_url;
    }
}

user.comment = function ()
{
    var mId = document.getElementById('movie_id').value;
    var title = document.getElementById('title_id').value;
    var content = document.getElementById('content_id').value;

    if (!dy.isEmpty(title) || !dy.isEmpty(content)) {
        alert('评论标题或内容为空！');
        return false;
    }

    if (dy.limit_length(title, 5, 50)) {
        alert('标题小于或大于50个字符！');
        return false;
    }

    if (dy.limit_length(title, 5, 150)) {
        alert('内容小于或大于150个字符！');
        return false;
    }

    if (dy.isLogin()) {
        alert('您没有登陆！');
        return false;
    }

    var url = 'comment/save';
    var param = 'id='+mId+'&title='+title+'&content='+content;
    var data = dy.ajax(url, param);

    if (data.error == '0') {
        alert('评论成功!');
        return true;
    }

    alert(data.msg);
}

user.init();

user.kao = function ()
{
	if (document.all) {
		document.body.style.behavior = 'url(#default#homepage)';
		document.body.setHomePage('http://www.dy1010.com');
		//alert('设置成功！')
	} else if (window.sidebar) {
		if (window.netscape) {
			try {
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			}
			catch (e) {
				//alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
			}
		}
		var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
		prefs.setCharPref('browser.startup.homepage', 'http://www.dy1010.com');
		//alert('设置成功！')
	} else {
		//alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
	}
}

//user.kao();